﻿using IntoTheVoid.Models;
using IntoTheVoid.Units;
using Prism.DryIoc;
using Prism.Ioc;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows;

namespace IntoTheVoid
{
	/// <summary>
	/// App.xaml 的交互逻辑
	/// </summary>
	public partial class App : PrismApplication
	{

		[DllImportAttribute("User32.dll")]
		private static extern int FindWindow(String ClassName, String WindowName);

		[DllImport("user32.dll")]
		public static extern bool SetForegroundWindow(int hWnd);

		[DllImport("user32.dll", EntryPoint = "ShowWindow", CharSet = CharSet.Auto)]
		public static extern int ShowWindow(IntPtr hwnd, int nCmdShow);

		Mutex mutex;
		protected override Window CreateShell()
		{
			return Container.Resolve<MainView>();
		}
		private void Application_Exit(object sender, ExitEventArgs e)
		{
			try
			{
				// 退出游戏进程
				LogHelper.Info("Application_Exit");
				foreach (Process p in Process.GetProcesses())
				{
					if (p.ProcessName.Contains("IntoTheVoid"))
					{
						var defaultPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Game");
						var path = BaseInfoContentModel.Instance.GetValue<string>("gameInstallPath", defaultPath);
						if (p.MainModule.FileName == path + "\\IntoTheVoid\\IntoTheVoid.exe")
						{
							try
							{
								p.Kill();
							}
							catch (Win32Exception)
							{
							}
						}
					}
				}
			}
			catch(Exception ex)
			{

			}

		}
		protected override void RegisterTypes(IContainerRegistry containerRegistry)
		{
			//containerRegistry.Register<IDialogHostService, DialogHostService>();

		}

		protected override void OnStartup(StartupEventArgs e)
		{
			mutex = new System.Threading.Mutex(true, "IntoTheVoid_Jinzhangshu");
			if (mutex.WaitOne(0, false))
			{
				base.OnStartup(e);
			}
			else
			{
				checkProcess();
			}

		}

		private void checkProcess()
		{
			Console.WriteLine("程序启动");
			Process current = Process.GetCurrentProcess();
			//获取启动进程名
			string strProcessName = Process.GetCurrentProcess().ProcessName;
			var processList = Process.GetProcessesByName(strProcessName);
			if (processList.Length > 1)
			{
				foreach (var process in processList)
				{
					if (process.Id == current.Id) continue;
					var hWnd = FindWindow(null, process.MainWindowTitle.ToString());
					ShowWindow((IntPtr)hWnd, 9);
					SetForegroundWindow(hWnd);
				}
				Environment.Exit(0);//退出程序
				return;
			}

		}
	}
}
